<template>
  <div class="page">
    <div class="flowchart-area">
      <div class="tree-area">
        <div class="menu-list">
          <i class="el-icon-plus pointer" @click="addFlowchart"></i>
          <i class="el-icon-edit pointer" @click="renameFlowchart"></i>
          <i class="el-icon-delete pointer" @click="deleteFlowchart"></i>
        </div>
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          class="user-tree"
          :data="groupLists"
          :props="defaultProps"
          @node-click="getTreeNode"
        >
          <div slot-scope="{ data }" class="custom-tree-node flex-row">
            <div class="line-limit">
              {{ data.name }}
            </div>
          </div>
        </el-tree>
      </div>
      <div class="flowchart-area">
        <flowchart-svg
          v-if="showFlow"
          ref="flowchart"
          @saveFlowchart="saveFlowchart"
          @deployFlowchart="deployFlowchart"
          @goNextPage="goNextPage"
        />
      </div>
    </div>

    <!-- 添加模板 -->
    <el-dialog
      :title="dialogText"
      :visible.sync="addDialogVisible"
      width="500px"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="模板名称" prop="templateName">
          <el-input
            v-model="ruleForm.templateName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input
            v-model="ruleForm.description"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTemplateSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 发起实例 -->
    <el-dialog
      title="发起实例"
      :visible.sync="launchDialogVisible"
      width="500px"
    >
      <el-form
        :model="launchForm"
        :rules="launchRules"
        ref="ruleForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="实例名称" prop="name">
          <el-input v-model="launchForm.name" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="launchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="launchSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import flowchartSvg from '@/views/components/flowchartSvg.vue'
import {
  getModel,
  createModel,
  updateModel,
  getModelInfo,
  saveModel,
  deployModel,
  deleteModel
} from '@/api/model.js'
import mockList from './mockInit.js'

export default {
  name: 'flowchart',
  components: {
    flowchartSvg
  },
  data() {
    return {
      showFlow: false,
      curNode: {},
      defaultkey: [1],
      defaultProps: {
        label: 'name'
      },
      groupLists: [
        // {
        //   created: null,
        //   createdBy: null,
        //   description: null,
        //   id: '137950241183825920',
        //   lastUpdated: null,
        //   lastUpdatedBy: null,
        //   modelComment: null,
        //   modelEditorJson: null,
        //   modelKey: null,
        //   modelType: null,
        //   name: '测试模板修改111',
        //   tenantId: null,
        //   thumbnail: null,
        //   version: null
        // },
        // {
        //   id: 2,
        //   name: '测试模板2'
        // }
      ],
      rules: {
        templateName: [
          { required: true, message: '输入不能为空', trigger: 'blur' }
        ]
      },
      addDialogVisible: false,
      ruleForm: {
        templateName: '',
        description: ''
      },
      dialogText: '添加模板',
      launchDialogVisible: false,
      launchForm: {
        name: ''
      },
      launchRules: {
        name: [{ required: true, message: '输入不能为空', trigger: 'blur' }]
      },
      launchData: {}
    }
  },
  methods: {
    getTreeNode(val) {
      console.log(val)
      this.curNode = val
      this.showFlow = false
      this.getModelInfo(val.id)
    },
    addFlowchart() {
      this.dialogText = '添加模板'
      this.addDialogVisible = true
      this.ruleForm = {}
    },
    renameFlowchart() {
      this.dialogText = '重命名'
      this.addDialogVisible = true
      this.ruleForm.templateName = this.curNode.name
      this.ruleForm.description = this.curNode.description
    },
    deleteFlowchart() {
      this.$confirm(`确定要删除『${this.curNode.name}}』吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.curNode, '当前节点')
        deleteModel(this.curNode.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.showFlow = false
          this.initMenuList()
        })
      })
    },
    addTemplateSubmit() {
      this.addDialogVisible = false
      if (this.dialogText === '添加模板') {
        const postData = {
          description: this.ruleForm.description,
          modelComment: '',
          modelKey: `doc_${Math.floor(Math.random() * 100)}`, // 随机数拼接modelKey
          name: this.ruleForm.templateName
        }
        this.addModel(postData)
      } else {
        const postData = {
          description: this.ruleForm.description,
          id: this.curNode.id || '',
          name: this.ruleForm.templateName
        }
        this.updateModel(postData)
      }
    },
    addModel(postData) {
      createModel(postData).then(res => {
        this.$message.success('添加模板成功')
        this.showFlow = false
        this.initMenuList(postData.modelKey)
      })
    },
    updateModel(postData) {
      updateModel(postData).then(res => {
        this.$message.success('修改成功')
        this.initMenuList()
      })
    },
    getModelInfo(modelId) {
      getModelInfo(modelId).then(res => {
        this.showFlow = true
        this.curNode.id = res.id
        this.curNode.name = res.name
        this.$nextTick(() => {
          this.$refs.flowchart.updateInitFun(JSON.parse(res.modelEditorJson))
          // this.$refs.flowchart.updateInitFun(mockList)
        })
      })
    },
    saveFlowchart(flowchartJson, svgBase64) {
      flowchartJson.documentation = this.curNode.description
      flowchartJson.id = this.curNode.id
      flowchartJson.name = this.curNode.name

      const saveData = {
        description: this.curNode.description || '',
        id: this.curNode.id,
        name: this.curNode.name,
        modelEditorJson: JSON.stringify(flowchartJson)
        // thumbnail: svgBase64
      }
      localStorage.setItem('测试', JSON.stringify(saveData))
      saveModel(saveData).then(() => {
        this.$message.success('保存成功')
      })
    },
    launchSubmit() {
      ;(this.launchData.name = this.launchForm.name),
        deployModel(this.launchData).then(() => {
          this.$message.success('创建实例成功')
          this.launchDialogVisible = false
        })
    },
    deployFlowchart(flowchartJson, svgBase64) {
      flowchartJson.documentation = this.curNode.description
      flowchartJson.id = this.curNode.id
      flowchartJson.name = this.curNode.name

      const saveData = {
        description: this.curNode.description || '',
        id: this.curNode.id,
        name: this.launchForm.name,
        modelEditorJson: JSON.stringify(flowchartJson),
        modelKey: this.curNode.modelKey || '123456'
        // thumbnail: svgBase64
      }
      this.launchData = saveData
      this.launchForm.name = ''
      this.launchDialogVisible = true
    },
    initMenuList(modelKey) {
      getModel().then(res => {
        this.groupLists = res
        if (!modelKey) {
          this.curNode = this.groupLists[0]
          this.getModelInfo(this.groupLists[0].id)
          this.$nextTick(() => {
            this.$refs['tree'].setCurrentKey(
              this.groupLists && this.groupLists[0].id
            )
          })
        } else {
          this.curNode = this.groupLists.filter(q => {
            return q.modelKey === modelKey
          })[0]

          this.getModelInfo(this.curNode.id)
          this.showFlow = true
          this.$nextTick(() => {
            this.$refs['tree'].setCurrentKey(this.curNode.id)
          })
        }
      })
    },
    goNextPage() {
      this.$router.push({
        name: 'list',
        params: { modelKey: this.curNode.modelKey }
      })
    }
  },
  created() {
    this.initMenuList()
  }
}
</script>

<style lang="less" scoped>
.pointer {
  cursor: pointer;
}
.page {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.flowchart-area {
  display: flex;
}
.tree-area {
  width: 240px;
  border-right: solid 1px #dcdcdc;

  .menu-list {
    margin: 10px;
    border-bottom: solid 1px #dcdcdc;
    i {
      padding: 8px;
    }
  }
}
.flowchart-area {
  width: calc(100%);
  height: 100%;
}
::v-deep .el-tree-node__content {
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  padding-left: 2px;
}
::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  padding: 0;
}
::v-deep .el-dialog__body {
  padding-bottom: 0px;
}
.line-limit {
  width: 220px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
